<?php
class OORDBMySQLTable extends OORDBTable
{
	private $database;
	private $connection;
	private $name;
	
	public function __construct( OORDBMySQLDatabase $database, $name )
	{
		$this->database = $database;
		$this->name = $name;
		$this->connection = $database->getConnection();
	}
	
	/**
	 * Get a single row from the table.
	 * @param mixed $id Primary key of row
	 * @return OORDBWrapper Row wrapper class
	 */
	public function get( $id )
	{
		$query = $this->connection->newSelectQuery();
		$table = $this->database->getName() . '.' . $this->name;
		$query->setSQL( "SELECT * FROM `$table` WHERE id = '".$query->escape($id)."'" );
		$query->execute();
		$iter = $query;
		if ( $iter->valid() )
		{
			$row = $iter->current();
			return new OORDBMySQLWrapper( $this, $row );
		}
		else
		{
			throw new OORDBRowNotFoundException( $this, $id );
		}
	}
	
	/**
	 * Get a list of all rows from the database.
	 * @return Iterator Iterator across a list of OORDBWrapper classes.
	 */
	public function getAll()
	{
		$query = $this->connection->newSelectQuery();
		$table = $this->database->getName() . '.' . $this->name;
		$query->setSQL( "SELECT * FROM $table" );
		$query->execute();
		$rows = new ArrayObject();
		foreach ( $query as $row )
		{
			$rows->append( new OORDBMySQLWrapper( $this, $row ) );
		}
		return $rows->getIterator();
	}
	
	/**
	 * Get the name of the table.
	 * @return string Name of table
	 */
	public function getName()
	{
		return $this->name;
	}
	
	/**
	 * Get the names of table fields.
	 * @return array Array of field names.
	 */
	public function getFields()
	{
		$query = $this->connection->newSelectQuery();
		$table = $this->database->getName() . '.' . $this->name;
		$query->setSQL( "DESCRIBE $table" );
		$query->execute();
		$rows = new ArrayObject();
		foreach ( $query as $row )
		{
			$values = array_values($row);
			$rows->append( $values[0] );
		}
		return $rows->getIterator();
	}
	
	/**
	 * Get the database this table belongs to.
	 * @return OORDBDatabase Parent database
	 */
	public function getDatabase()
	{
		return $this->database;
	}
}
?>